package com.hunterai.dao;

import com.hunterai.entity.GenerateTask;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.*;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public interface GenerateTaskRepository extends JpaRepository<GenerateTask, Long> {
    GenerateTask findByTaskId(String taskId);

    // 查找排队中优先级最高且最早的任务
    @Query(value = "SELECT * FROM generate_task WHERE status = 'QUEUED' ORDER BY piority ASC, created_at ASC LIMIT 1 FOR UPDATE SKIP LOCKED", nativeQuery = true)
    GenerateTask findNextQueuedTaskForUpdate();
    
    // 根据用户ID查找任务
    List<GenerateTask> findByUserIdOrderByCreatedAtDesc(Long userId);
    
    // 根据任务ID和用户ID查找任务（确保用户只能查看自己的任务）
    GenerateTask findByTaskIdAndUserId(String taskId, Long userId);

    // 分页查询用户的任务历史
    Page<GenerateTask> findByUserIdOrderByCreatedAtDesc(Long userId, Pageable pageable);

    Page<GenerateTask> findByUserIdAndWorkflowId(Long userId, String workflowId, Pageable pageable);
}